﻿// See https://aka.ms/new-console-template for more information

// Construct a ConcurrentQueue.

using System.Collections.Concurrent;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using ConsoleApp;
using ConsoleApp.DesignPatterns;
using ConsoleApp.Tree;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.Streaming;
using NPOI.XSSF.UserModel;



// 构建邻接表数据
var nodes = new List<(string, int?)>
{
    ("Root", null),
    ("Child1", 0),
    ("Child2", 0),
    ("Grandchild1", 1),
    ("Grandchild2", 1)
};
 
// 构建树
var root = TreeBuilder.BuildTree(nodes);
 
// 遍历操作
Console.WriteLine("深度优先遍历：");
foreach (var node in root.DepthFirst())
    Console.WriteLine(node);
 
Console.WriteLine("\n广度优先遍历：");
foreach (var node in root.BreadthFirst())
    Console.WriteLine(node);

return;
// SXSSF - 流式写入 (合并单元格的行号必须全部在内存中)
// var workbook = new SXSSFWorkbook(100); // 仅保留最近 100 行在内存
// var sheet = workbook.CreateSheet("Sheet1");
//  
// for (var i = 0; i < 1_000_000; i++)
// {
//     var row = sheet.CreateRow(i);
//     row.CreateCell(0).SetCellValue($"Row {i}");
// }
//  
// using (var stream = new FileStream("large.xlsx", FileMode.Create))
// {
//     workbook.Write(stream);
// }

// 创建 XSSFWorkbook
var workbook = new XSSFWorkbook();
var sheet = workbook.CreateSheet("合并示例");
 
// 合并 A1:D3（3 行 4 列） 从 0 开始的索引（即 (0, 0, 0, 2) 表示第 1 行、A 到 C 列）。
var region = new CellRangeAddress(0, 2, 0, 3);
sheet.AddMergedRegion(region);
 
// 设置合并单元格的样式
var style = workbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.Center;
style.VerticalAlignment = VerticalAlignment.Center;
style.WrapText = true; // 自动换行
style.BorderTop = BorderStyle.Thin;
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
 
// 写入数据到合并后的单元格（左上角）
var firstRow = sheet.CreateRow(0);
var cell = firstRow.CreateCell(0);
cell.SetCellValue("这是一个合并了 3 行 4 列的单元格\n支持自动换行");
cell.CellStyle = style;
 
// 可选：为合并区域内的其他单元格设置样式（避免导出时样式异常）
for (var i = region.FirstRow; i <= region.LastRow; i++)
{
    var row = sheet.GetRow(i) ?? sheet.CreateRow(i);
    for (var j = region.FirstColumn; j <= region.LastColumn; j++)
    {
        var c = row.GetCell(j) ?? row.CreateCell(j);
        c.CellStyle = style;
    }
}
 
// 写入文件
using (var fs = new FileStream("AdvancedMergedCells_XSSF.xlsx", FileMode.Create))
{
    workbook.Write(fs);
}
return;

var categories = new List<CategoryDto>
{
    new() { Id = 1, Name = "1", ParentId = null },
    new() { Id = 2, Name = "1 - 2", ParentId = 1 },
    new() { Id = 3, Name = "1 - 2", ParentId = 1 },
    new() { Id = 4, Name = "1 - 2", ParentId = 1 },
    new() { Id = 5, Name = "1 - 2 - 3", ParentId = 3 },
    new() { Id = 6, Name = "1 - 2 - 3", ParentId = 4 }
};

CategoryNode BuildTree(List<CategoryDto> dtoList)
{
    var lookup = dtoList.ToLookup(x => x.ParentId); // 使用Lookup来快速查找所有具有相同ParentId的项
    var root = new CategoryNode { Id = 1, Name = "Root" }; // 假设有一个根节点，其ParentId为null或0
    var queue = new Queue<CategoryNode>(); // 使用队列进行层次遍历
    queue.Enqueue(root); // 将根节点加入队列
 
    while (queue.Count > 0)
    {
        var currentNode = queue.Dequeue();
        foreach (var childDto in lookup[currentNode.Id]) // 查找所有具有当前节点Id作为ParentId的项
        {
            var childNode = new CategoryNode { Id = childDto.Id, Name = childDto.Name };
            currentNode.Children.Add(childNode); // 将子节点添加到当前节点的子节点列表中
            queue.Enqueue(childNode); // 将子节点加入队列以供后续处理
        }
    }
    return root; // 返回根节点，它现在包含了完整的树形结构
}


var treeRoot = BuildTree(categories);

Console.WriteLine(JsonSerializer.Serialize(treeRoot));

//Process.Start("D:\\Program Files\\Tencent\\WeChat\\WeChat.exe");

// var numbers = new List<int> { 143448288, 143448291, 143448293, 143448314, 143448356, 143453983, 143455320, 143456172, 143456217, 143456539, 143456585, 143456616, 143457199, 143457215, 143457231, 143457239, 143457254, 143457273, 143457276, 143457557, 143457881, 143457896, 143457901, 143457998, 143458007, 143458022, 143458065, 143458078, 143458096, 143458130, 143458227, 143466561, 143466579, 143466601, 143466622, 143466638, 143466658, 143466709, 143466792, 143466805, 143467106, 143467207, 143467226, 143467255, 143467270, 143467289, 143467298, 143467301, 143467308, 143467314 };
// // 方法1：使用LINQ
// var duplicates1 = numbers.GroupBy(n => n)
//     .Where(g => g.Count() > 1)
//     .Select(g => g.Key)
//     .ToList();
//  
// foreach (var num in duplicates1)
// {
//     Console.WriteLine(num);
// }
//
// var duplicates2 = numbers.Where(n => numbers.Count(m => m == n) > 1)
//     .Distinct()
//     .ToList();
//  
// foreach (var num in duplicates2)
// {
//     Console.WriteLine(num);
// }

// 方法2：使用哈希表（Dictionary）
// var countDict = new Dictionary<int, int>();
// var duplicates = new List<int>();
//  
// foreach (var num in numbers)
// {
//     if (!countDict.TryAdd(num, 1))
//     {
//         countDict[num]++;
//     }
// }
//  
// foreach (var kvp in countDict)
// {
//     if (kvp.Value > 1)
//     {
//         duplicates.Add(kvp.Key);
//     }
// }
//  
// foreach (var num in duplicates)
// {
//     Console.WriteLine(num); // 输出重复的数字
// }

// 方法3：使用HashSet

return; 
var list11 = new List<Dto>
{
    new(){ Id = 1, Name = "11", Age = 1 },
    new(){ Id = 2, Name = "22", Age = 2 },
    new(){ Id = 3, Name = "33", Age = 3 }
};

var list22 = new List<Dto>
{
    new(){ Id = 2, Name = "22", Age = 1 },
    new(){ Id = 3, Name = "33", Age = 2 },
    new(){ Id = 4, Name = "44", Age = 3 }
};

// 合并销量
list11.AddRange(list22);//skus.Concat(combineSkus); // 注意: 合并可能存在问题
        
// 分组统计销量
var mergedList = list11
    .GroupBy(dto => dto.Name)
    .Select(group => new Dto
    {
        Name = group.Key,
        Age = group.Sum(dto => dto.Age)
    })
    .ToList();

foreach (var dto in mergedList)
{
    Console.WriteLine(dto.Name + ": " + dto.Age);
}

return;

List<Dto> list1 =
[
    new() { Id = 1, Name = "A" },
    new() { Id = 2, Name = "B" },
    new() { Id = 3, Name = "A" },
    new() { Id = 4, Name = "B" },
    new() { Id = 5, Name = "C" }
];
 
var list2 = list1
    .GroupBy(d => d.Name)
    .Select(g => g.OrderByDescending(d => d.Id).First())
    .ToList();
 
foreach (var item in list2)
{
    Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");
}

// 获取list1与list2的差集，即list1中有而list2中没有的元素
var difference = list1.Except(list2).ToList();

foreach (var item in difference)
{
    Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");
}

return;

var filePaths = "D:\\联行号20200114.txt";
var encoding = Encoding.GetEncoding(54936);
// 读取文件的全部内容
string fileContent = File.ReadAllText(filePaths, encoding); // 54936 : GB18030 

// 去除不可打印字符
string cleanedContent = Regex.Replace(fileContent, @"[^\x00-\x7F]+", string.Empty);

File.WriteAllText("D:\\联行号.txt", cleanedContent, encoding);

return;

//我们模拟了一个简单的数据更新和缓存更新的场景。当主题（ConcreteSubject）的数据发生变化时，所有注册的观察者（ConcreteObserver）都会收到通知并更新自己的缓存
var subject = new ConcreteSubject();  
var observer1 = new ConcreteObserver();  
var observer2 = new ConcreteObserver();  
  
subject.RegisterObserver(observer1);  
subject.RegisterObserver(observer2);  
  
subject.Data = "New data"; // 触发通知，观察者更新缓存  
  
// 取消注册一个观察者  
subject.UnregisterObserver(observer1);  
  
subject.Data = "Another new data"; // 仅observer2会收到通知并更新缓存  

//new DemoFileExport().Read1();
return;

//XXX正由另一进程使用，因此该进程无法访问此文件: 文件还没关闭就被操作
// 方式一: 文件锁
using (var fs = new FileStream("path_to_your_file", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
    // 写入文件的代码
}

// 方式二: 互斥锁
var mutex = new Mutex(false, "MyUniqueMutexIdentifier");
try
{
    // 等待获取互斥锁
    mutex.WaitOne();
    
    
}
finally
{
    // 释放互斥锁
    mutex.ReleaseMutex();
}

return;
//var create = "CREATE TABLE MyTable(Id INT, Name TEXT);";

//var ins = 
//DemoSqlite.ExecSQL(create);

//string strSql = "select * from AddressSteing";
//DataSet ds = DemoSqlite.ExecuteQuery(strSql);
//if (ds != null && ds.Tables.Count > 0)
//{
//    var DataSource = ds.Tables[0];
//    foreach (DataRow row in DataSource.Rows)
//    {
//        Console.WriteLine(row.ToString());
//    }
//}

return;

var ids = new int[] { 4, 8, 6, 14, 5 };
// 输出数组的内容
foreach (var id in ids)
{
    Console.WriteLine(id);
}
return;

var dateString = "2024-01-12 17:00:00";
DateTime date = DateTime.Parse(dateString);

// 获取当前日期
DateTime today = DateTime.Today;

// 比较日期
if (date.Date == today)
{
    Console.WriteLine("日期是今天");
}

Console.WriteLine(111);

return;

// 文件
string filePath = @"D:\20231125log.txt"; // 替换为您的文件路径
var lines = File.ReadAllLines(filePath).Reverse(); // 读取所有行并反转
var last5Lines = lines.Take(4).Reverse(); // 获取最后5行并反转

// 打印最后5行


//Console.WriteLine(string.Join("\\n", last5Lines));

var content = "";
foreach (string line in last5Lines)
{
    content += line;
    Console.WriteLine(line);
}

if (content.Contains("程序异常"))
{
    Console.WriteLine(content.Trim());
}

return;
//在C#中，有多种方法可以去除字符串中的空格。以下是一些常见的方法：
//  使用String.Trim()方法：
string originalString = "   Hello World!   ";
string trimmedString = originalString.Trim();
Console.WriteLine(trimmedString); // 输出 "Hello World!"

// 使用String.TrimStart()或String.TrimEnd()方法：
string trimmedStartString = originalString.TrimStart();
string trimmedEndString = originalString.TrimEnd();
Console.WriteLine(trimmedStartString); // 输出 "Hello World!   "
Console.WriteLine(trimmedEndString); // 输出 "   Hello World!"

// 使用String.Replace()方法：
string replacedString = originalString.Replace(" ", "");
Console.WriteLine(replacedString); // 输出 "HelloWorld!"

//var info = SystemInfoHelper.GetInstanceNames("Network Interface");
//Console.WriteLine(JsonConvert.SerializeObject(info));

//SystemInfoHelper.GetNetwork();



//SystemInfoHelper.GetPerformanceCounterCounterNames("Network Interface", "Realtek PCIe GbE Family Controller");//"PhysicalDisk", "_total"



return; 

//ASP.NET 获取项目目录
//string projectPath = Server.MapPath("&#126;");


//DemoCsv.Save();

//WeChatRefund("", "", 60, 111.34, 0.34, 0);

//var str = "20230920164424";
//var date = DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
//onsole.WriteLine(date);

//Console.WriteLine(date.ToString("yyyyMMddHHmmss"));

//Console.WriteLine(DateTime.Now.ToString(""));
return;


var firstMoney = 100m;
var lastMoney = 100m;
var quarterMoney = 100m;


return; 

string documentPath = "D:\\LC-BH_BH-20230902-0001.docx";
//using (WordprocessingDocument document = WordprocessingDocument.Open(documentPath, false))
//{
    //Body body = document.MainDocumentPart.Document.Body;
    //Console.WriteLine(body.InnerText);
    
    
    //在这里进行文档解析操作
    // 获取文档中的所有段落
    //foreach (Paragraph paragraph in document.MainDocumentPart.RootElement.Descendants<Paragraph>())
    //{
//        Console.WriteLine(paragraph.InnerText);
        
        // 遍历每个Run
        // foreach (var run in paragraph.Descendants<Run>())
        // {
        //     
        //     // 遍历每个Text
        //     foreach (var text in run.Descendants<Text>())
        //     {
        //         // 打印文本内容
        //         //words.Add(text.Text);
        //         Console.WriteLine(text.Text);
        //     }
        // }
   // }
//}

return; 
var input = "String to Encode.";
var mod = "MTA1MzQxNzIwODA3NjUwNzg5NDY4ODU2Mjc0NDA3ODIwMjQ1ODQ5NDE1MDk1MDIzMTM3MjM0NzAwNzYzNjc2MTgwNjg3ODMxMjA3NTY0NTcxMjg2MzM4NjQ1NzEwMDcyMjY2MTQyNDIzMTczMjkwMDk0MTc0MTA5MTc5MzI0NjYwMjQ4NzI3NzM0MTQ5NDY0MjUwODkwOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXc2OTAzNjc3NzQzODM3NzM0MjE2ODM0NjY4MjM4MTQ0OTA3MDQ3MTk1Njc1NzU3OTE2NjEyNzkzMzM2MzI3MDUyNjg0NDI5NDExNjI2MzA0MzM5==";
var exp = "NjU1Mzc=";
var intValue = int.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(exp)));

var rsaParam = new RSAParameters();
rsaParam.Modulus = Convert.FromBase64String(mod);
rsaParam.Exponent = BitConverter.GetBytes(intValue);
using (var rsa = new RSACryptoServiceProvider())
{
    rsa.ImportParameters(rsaParam);
    Console.WriteLine(Convert.ToBase64String(rsa.Encrypt(Encoding.UTF8.GetBytes(input), false)));
}
Console.ReadLine();



return; 

double a;
double b;

a = 1.2d;
b = 2.3d;

float x = 0.7f;


decimal price;
decimal discount;
decimal discount_price;

//注意：必须要带“m”,否则将和标准的浮点类型一样。而我们要求的却是用来计算货币类的浮点数，但是可以给其赋整数值。
// decimal 对小数的运算更加的准确。
price = 19.95m;
discount = 0.15m; 
//discount rate is 15%

discount_price = price - (price * discount);

Console.WriteLine("Discounted price :$ " + discount_price);

Console.ReadKey();

Stopwatch sw = Stopwatch.StartNew();

string inputString = "hello, world!";

// concurrent dictionary code
ConcurrentDictionary<char, int> concurrentDictionary = new ConcurrentDictionary<char, int>();

foreach (char c in inputString)
{
    concurrentDictionary.AddOrUpdate(c, 1, (key, oldValue) => ++oldValue);
}

foreach (var kvp in concurrentDictionary.OrderBy(x => x.Key))
{
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

sw.Stop();
Console.WriteLine($"ConcurrentDictionary Elapased Time: {sw.ElapsedMilliseconds}");

sw = Stopwatch.StartNew();

// dictionary with lock code
Dictionary<char, int> dictionary = new Dictionary<char, int>();
object lockObject = new object();

foreach (char c in inputString)
{
    lock (lockObject)
    {
        if (!dictionary.ContainsKey(c))
        {
            dictionary[c] = 1;
        }
        else
        {
            ++dictionary[c];
        }
    }
}

foreach (var kvp in dictionary.OrderBy(x => x.Key))
{
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

sw.Stop();
Console.WriteLine($"Dictionary with Lock Elapased Time: {sw.ElapsedMilliseconds}");



return;



//1.匹配日期格式：yyyy-MM-dd HH:mm:ss
String timeRegex = "^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))\\s+([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
Console.WriteLine(Regex.IsMatch("2012-12-31 12:07:59", timeRegex));


//2.匹配日期格式：yyyy-MM-dd
String timeRegex1 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|"+
                    "((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|"+
                    "((0[48]|[2468][048]|[3579][26])00))-02-29)$";
 
Console.WriteLine(Regex.IsMatch("2018-11-30", timeRegex1));


//3.匹配日期格式：yyyy/MM/dd

String timeRegex2 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})\\/(((0[13578]|1[02])\\/(0[1-9]|[12][0-9]|3[01]))|"+
"((0[469]|11)\\/(0[1-9]|[12][0-9]|30))|(02\\/(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|"+
"((0[48]|[2468][048]|[3579][26])00))\\/02\\/29)$";
 
Console.WriteLine(Regex.IsMatch("2018/12/31", timeRegex2));


//4.匹配日期格式：yyyy/MM/dd HH:mm:ss

String timeRegex3 = "((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})\\/(((0[13578]|1[02])\\/(0[1-9]|[12][0-9]|3[01]))|"+
"((0[469]|11)\\/(0[1-9]|[12][0-9]|30))|(02\\/(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|"+
"((0[48]|[2468][048]|[3579][26])00))\\/02\\/29))\\s([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
 
Console.WriteLine(Regex.IsMatch("2018/12/30 12:29:59", timeRegex3));


//5.匹配日期格式：yyyyMMdd

String timeRegex4 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|"+
"((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|"+
"((0[48]|[2468][048]|[3579][26])00))0229)$";
 
Console.WriteLine(Regex.IsMatch("20181223", timeRegex4));


//6.匹配日期格式：yyyyMMddHHmmss

String timeRegex5 = "((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|"+
"((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229))"+
"([0-1][0-9]|2[0-3])([0-5][0-9])([0-5][0-9])$";
 
Console.WriteLine(Regex.IsMatch("20181228162437", timeRegex5));


//7.匹配格式：yyyyMMddHHmmssSSS

String timeRegex6 = "((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|"+
"((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|"+
"((0[48]|[2468][048]|[3579][26])00))0229))([0-1][0-9]|2[0-3])([0-5][0-9])([0-5][0-9])([0-9]{3})$";
 
Console.WriteLine(Regex.IsMatch("20181227182439000", timeRegex6));


//8.匹配格式：yyyyMMdd HH:mm:ss

String timeRegex7 = "((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|"+
"((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|"+
"((0[48]|[2468][048]|[3579][26])00))0229))\\s([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
 
Console.WriteLine(Regex.IsMatch("20181227 07:20:36", timeRegex7));

return;

//1. 字符串转换成字节数组byte[]：
// string str = "This is test string";
// byte[] byteArray = System.Text.Encoding.Default.GetBytes(str);
// //2.字节数组换成字符串：
// byte[] byteArray = 通过某种方式获取到的字节数组
// string str = System.Text.Encoding.Default.GetString(byteArray);

return;

ConcurrentQueue<int> cq = new ConcurrentQueue<int>();
for (var i = 0; i < 10; i++)
{
    cq.Enqueue(i);
}

Random random = new Random(); 
var timer = new Timer(d =>
{
    int result;
    cq.TryDequeue(out result);
    if (result == 0) 
    {
        return;
    }
    //默认业务耗时
    var t = random.Next(10, 30) * 100;
    Console.WriteLine(result + " 开始执行");
    Thread.Sleep(t);
    Console.WriteLine(result + " 执行完成 " + t);
});
timer.Change(0, 500);

// Thread SaveorderThread = new Thread(t =>
// {
//     while (true)
//     {
//         Thread.Sleep(500);
//         int result;
//         cq.TryDequeue(out result);
//         if (result == 0)
//         {
//             continue;
//         }
//         Console.WriteLine(result + " 开始执行");
//         Random random = new Random(); 
//         //默认业务耗时
//         var n = random.Next(1, 10) * 100;
//         Thread.Sleep(n);
//         Console.WriteLine(result + " "+ n + " 执行完成 " + t);
//     }
// });
// SaveorderThread.Start();

Thread.Sleep(100000);
Console.WriteLine("-----------");

return; 

// // Peek at the first element.
// if (!cq.TryPeek(out result))
// {
//     Console.WriteLine("CQ: TryPeek failed when it should have succeeded");
// }
// else if (result != 0)
// {
//     Console.WriteLine("CQ: Expected TryPeek result of 0, got {0}", result);
// }

// Random random = new Random(); 
// var timer = new Timer(d =>
// {
//     int result;
//     cq.TryDequeue(out result);
//     if (result == 0) 
//     {
//         return;
//     }
//     //默认业务耗时
//     var t = random.Next(10, 30) * 100;
//     Console.WriteLine(result + " 开始执行");
//     Thread.Sleep(t);
//     Console.WriteLine(result + " 执行完成 " + t);
// });
// timer.Change(0, 500);

// RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,defaultDatabase=0"));
// Random random = new Random(); 
// var timer = new Timer(d =>
// {
//     int result;
//     cq.TryPeek(out result);
//     if (result == 0) 
//     {
//         return;
//     }
//
//     var key = result.ToString();
//     if (RedisHelper.Exists(key))
//     {
//         return;
//     }
//     RedisHelper.Set(key, 1);
//     
//      //默认业务耗时
//     Console.WriteLine(result + " 开始执行");
//     var t = random.Next(10, 30) * 100;
//     Thread.Sleep(t);
//     Console.WriteLine(result + " 执行完成 " + t);
//     cq.TryDequeue(out result);
//     RedisHelper.Del(key);
// });
// timer.Change(0, 500);

// while (cq.TryPeek(out result))
// {
//     Thread.Sleep(result * 1000);
//     
//     int localValue;
//     cq.TryDequeue(out localValue);
//     Console.WriteLine(localValue);
// }


Thread.Sleep(100000);
Console.WriteLine("-----------");

// int outerSum = 0;
// // An action to consume the ConcurrentQueue.
// var action = () =>
// {
//     int localSum = 0;
//     int localValue;
//     while (cq.TryDequeue(out localValue)) localSum += localValue;
//     Interlocked.Add(ref outerSum, localSum);//以原子操作的形式，添加两个整数并用两者的和替换第一个整数
// };
//
// // Start 4 concurrent consuming actions.
// Parallel.Invoke(action, action, action, action);
//
// Console.WriteLine("outerSum = {0}, should be 49995000", outerSum);


// 使用Parallel的Invoke函数时需要特别注意以下量两点：1、函数执行不要求特定的顺序。2、函数执行必须独立的,不存在特定的依赖关系
// Parallel.For---为固定数目的独立For循环迭代提供负载均衡的潜在的并行执行。
// Parallel.ForEach---为固定数目的独立For Each循环迭代提供负载均衡的潜在的并行执行。这种方法支持自定义分区类，这是你可以完全控制数据的分布。
// Parallel.Invok---对独立的任务提供潜在的并行执行。